using System;
using System.Collections.ObjectModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Core.Mapping;
using Core.Graphics;

namespace WorldEditor
{
    /// <summary>
    /// Holds a collection of all Bitmpa representations of the TileSetTiles.
    /// </summary>
    public class TileSetTileBitmaps : System.Collections.Generic.Dictionary<TileID, System.Drawing.Bitmap> 
    {
        public static TileSetTileBitmaps GlobalTileBitmaps = new TileSetTileBitmaps();

        public static System.Drawing.Bitmap GetTileBitmap(TileID id, TileSetTypes TileSettypes)
        {
            //if GlobalTerrainTileBitmaps is an empty tile, return empty bitmap.
            if (id == TileID.EmptyID)
            {
                return _Empty;
            }

            //Check to see if GlobalTerrainTileBitmaps is a pre-loaded bitmap tile exists.  If so return it.
            if (GlobalTileBitmaps.ContainsKey(id))
            {
                return GlobalTileBitmaps[id];
            }
            //If bitmap not found create it, save to collection, and return it.
            //First load TileSetTile
            TileSetTile tst = TileSetCollection.GetTile(id, TileSettypes);
            int Width = tst.SourceRectangle.Width;
            int Height = tst.SourceRectangle.Height;
            //Color Array
            Color[] data = new Color[Width * Height];
            //Get array of Colors
            tst.Parent.TileSetTexture.GetData<Color>(0, tst.SourceRectangle, data, 0, Height * Width);

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Width, Height);

            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    Color cl = data[y * Width + x];
                    bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(cl.A, cl.R, cl.G, cl.B));
                }
            }
            //Set Bitmap so that if we need GlobalTerrainTileBitmaps again it will be available;
            GlobalTileBitmaps.Add(id,bmp);

            return bmp;
        }

        private static System.Drawing.Bitmap _Empty = new System.Drawing.Bitmap(Tile.TileWidth, Tile.TileHeight);

    }
}